import React, { useEffect, useState } from 'react';
import { Modal, Upload, Button, message, Form, Spin } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import EditorFile from '@/components/fileEditor';
import { genWarnLawHtml, genWarnLawPdf, urgeFileUpload } from '@/services/public';

interface UploadLegaProps {
  visible: boolean;
  info: any;
  businessType: 1 | 2 | 3;
  cancel: () => void;
  onSubmit: () => void;
}

const UploadLega: React.FC<UploadLegaProps> = ({
  visible,
  cancel,
  onSubmit,
  info,
  businessType,
}) => {
  const [form] = Form.useForm();
  const [editContent, setEditContent] = useState<any>('');
  const [editVisible, setEditVisible] = useState<boolean>(false);
  const [isLoading, setLoading] = useState<boolean>(false);
  const [lawAmendFileList, setLawAmendFileList] = useState<any>([]);
  const [lawInvestigationFileList, setLawInvestigationFileList] = useState<any>([]);

  const formatUploadFile = (list) => {
    let str = '';
    if (!list || !list.length) {
      return;
    }
    list.map((item, index) => {
      if (index == list.length - 1) {
        str += item.response.data.fileId;
      } else {
        str += item.response.data.fileId + ',';
      }
    });
    return str;
  };

  const handleSubmit = async () => {
    const formValues = await form.validateFields();
    setLoading(true);
    const params: any = {
      corpProjectId: info.id,
    };
    if (formValues.amendFile) {
      if (businessType == 1) {
        params.specialAccountAmendFileId = formatUploadFile(formValues.amendFile.fileList);
      } else if (businessType == 2) {
        params.rightProtectionAmendFileId = formatUploadFile(formValues.amendFile.fileList);
      } else if (businessType == 3) {
        params.lzUserAmendFileId = formatUploadFile(formValues.amendFile.fileList);
      }
    }
    if (formValues.notifyFile) {
      if (businessType == 1) {
        params.specialAccountNotifyFileId = formatUploadFile(formValues.notifyFile.fileList);
      } else if (businessType == 2) {
        params.rightProtectionNotifyFileId = formatUploadFile(formValues.notifyFile.fileList);
      } else if (businessType == 3) {
        params.lzUserNotifyFileId = formatUploadFile(formValues.notifyFile.fileList);
      }
    }
    if(!formValues.amendFile&&!formValues.notifyFile) {
      cancel()
      return
    }
    const res = await urgeFileUpload(params);
    setLoading(false);
    if (res && res.success) {
      onSubmit();
    } else {
      message.error(res.errMsg || '错误');
    }
  };

  const handleDownload = async (content: any) => {
    const res = await genWarnLawPdf({
      corpProjectId: info.id,
      html: content,
    });
    if (res && res.success) {
      setEditVisible(false);
      setEditContent('');
      window.open(res.data);
    } else {
      message.error((res && res.errMsg) || '请求失败');
    }
  };

  const handleEdit = async (type: 1 | 2) => {
    const res = await genWarnLawHtml({
      corpProjectId: info.id,
      businessType,
      type,
    });
    if (res && res.success) {
      setEditContent(res.data);
      setEditVisible(true);
    } else {
      message.error((res && res.errMsg) || '请求失败');
    }
  };

  const handleLawInvestigationFileChange = ({ file, fileList }) => {
    setLawInvestigationFileList(() => {
      const newList = fileList.map((item) => {
        const item1 = Object.assign(item, item.response ? item.response.data : {});
        item1.type = item.originFileObj.type;
        return item1;
      });
      return newList;
    });
  };

  const handleLawAmendFileChange = ({ file, fileList }) => {
    setLawAmendFileList(() => {
      const newList = fileList.map((item) => {
        const item1 = Object.assign(item, item.response ? item.response.data : {});
        item1.type = item.originFileObj.type;
        return item1;
      });
      return newList;
    });
  };

  const titleCheck = () => {
    let tit = '上传法律文书';
    switch (businessType) {
      case 1:
        tit = '工资专户账户法律文书上传';
        break;
      case 2:
        tit = '维权告示牌法律文书上传';
        break;
      case 3:
        tit = '劳资专员法律文书上传';
        break;
      default:
        break;
    }
    return tit;
  };

  return (
    <>
      <Modal
        title={titleCheck()}
        closable={true}
        onCancel={cancel}
        visible={visible}
        maskClosable={false}
        confirmLoading={isLoading}
        okText="确认"
        cancelText="取消"
        onOk={handleSubmit}
        width="600px"
      >
        <Spin spinning={isLoading} tip="请稍等...">
          <Form form={form}>
            <Form.Item
              label="调查询问通知书(盖章版)"
              name="notifyFile"
              extra={
                <div style={{ paddingTop: '5px' }}>
                  <a onClick={() => handleEdit(1)}>点击编辑/下载调查询问通知书</a>
                </div>
              }
              // rules={[{ required: true }]}
            >
              <Upload
                name="file"
                action="/api/upload/resource"
                onChange={handleLawInvestigationFileChange}
                data={{
                  ossEnum: 'PROJECT',
                }}
                accept={'image/*,.pdf'}
              >
                <Button icon={<UploadOutlined />}>点击上传盖章后文件</Button>
              </Upload>
            </Form.Item>
            <Form.Item
              label="改正指令书(盖章版)"
              name="amendFile"
              extra={
                <div style={{ paddingTop: '5px' }}>
                  <a onClick={() => handleEdit(2)}>
                    点击编辑/下载改正指令书
                  </a>
                </div>
              }
              // rules={[{ required: true }]}
            >
              <Upload
                name="file"
                action="/api/upload/resource"
                onChange={handleLawAmendFileChange}
                data={{
                  ossEnum: 'PROJECT',
                }}
                accept={'image/*,.pdf'}
              >
                <Button icon={<UploadOutlined />}>点击上传盖章后文件</Button>
              </Upload>
            </Form.Item>
          </Form>
        </Spin>
      </Modal>
      {editVisible ? (
        <EditorFile
          visible={editVisible}
          onCancel={() => {
            setEditVisible(false);
          }}
          editContent={editContent}
          onSubmit={handleDownload}
        />
      ) : null}
    </>
  );
};

export default UploadLega;
